<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.0.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">

<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Monda:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">
<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"favourite-s.gitee.io","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":true},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="在工作中我们打交道最多的页面控件可能就是TableView或者Collectionview了，而很多时候cell的高度是无法确定的。随着硬件的升级，我们也会采用系统的高度自动计算。 在这其中，我们可能会使用约束进行布局。也可能会自己计算高度，如果一个TableView有多个cell，而其中个别的cell我们希望使用系统的自动布局，我们需要实现以下步骤：">
<meta property="og:type" content="article">
<meta property="og:title" content="iOS中UICollectionViewCell和UITableViewCell自动计算">
<meta property="og:url" content="http://favourite-s.gitee.io/2020/08/07/iOS%E4%B8%ADUICollectionViewCell%E5%92%8CUITableViewCell%E8%87%AA%E5%8A%A8%E8%AE%A1%E7%AE%97/index.html">
<meta property="og:site_name" content="左手边是幸福">
<meta property="og:description" content="在工作中我们打交道最多的页面控件可能就是TableView或者Collectionview了，而很多时候cell的高度是无法确定的。随着硬件的升级，我们也会采用系统的高度自动计算。 在这其中，我们可能会使用约束进行布局。也可能会自己计算高度，如果一个TableView有多个cell，而其中个别的cell我们希望使用系统的自动布局，我们需要实现以下步骤：">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2020-08-07T02:25:03.000Z">
<meta property="article:modified_time" content="2020-08-20T02:21:05.746Z">
<meta property="article:author" content="favourite_s">
<meta property="article:tag" content="iOS">
<meta property="article:tag" content="UICollectionView">
<meta property="article:tag" content="UITableViewCell">
<meta property="article:tag" content="UICollectionViewCell">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="http://favourite-s.gitee.io/2020/08/07/iOS%E4%B8%ADUICollectionViewCell%E5%92%8CUITableViewCell%E8%87%AA%E5%8A%A8%E8%AE%A1%E7%AE%97/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>iOS中UICollectionViewCell和UITableViewCell自动计算 | 左手边是幸福</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="左手边是幸福" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">左手边是幸福</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">知识总结</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-commonweal">

    <a href="/404/" rel="section"><i class="fa fa-heartbeat fa-fw"></i>公益 404</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://favourite-s.gitee.io/2020/08/07/iOS%E4%B8%ADUICollectionViewCell%E5%92%8CUITableViewCell%E8%87%AA%E5%8A%A8%E8%AE%A1%E7%AE%97/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="favourite_s">
      <meta itemprop="description" content="只要胆子大，底牌全是炸">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="左手边是幸福">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          iOS中UICollectionViewCell和UITableViewCell自动计算
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2020-08-07 10:25:03" itemprop="dateCreated datePublished" datetime="2020-08-07T10:25:03+08:00">2020-08-07</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-08-20 10:21:05" itemprop="dateModified" datetime="2020-08-20T10:21:05+08:00">2020-08-20</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/iOS/" itemprop="url" rel="index"><span itemprop="name">iOS</span></a>
                </span>
            </span>

          <br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="far fa-file-word"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>1.3k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="far fa-clock"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>1 分钟</span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>在工作中我们打交道最多的页面控件可能就是<code>TableView</code>或者<code>Collectionview</code>了，而很多时候<code>cell</code>的高度是无法确定的。随着硬件的升级，我们也会采用系统的高度自动计算。</p>
<p>在这其中，我们可能会使用约束进行布局。也可能会自己计算高度，如果一个<code>TableView</code>有多个cell，而其中个别的cell我们希望使用系统的自动布局，我们需要实现以下步骤：</p>
<a id="more"></a>

<h2 id="正文"><a href="#正文" class="headerlink" title="正文"></a>正文</h2><h3 id="设置代理和数据源，实现代理方法"><a href="#设置代理和数据源，实现代理方法" class="headerlink" title="设置代理和数据源，实现代理方法"></a>设置代理和数据源，实现代理方法</h3><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">tableView</span><span class="params">(<span class="number">_</span> tableView: UITableView, heightForRowAt indexPath: IndexPath)</span></span> -&gt; <span class="type">CGFloat</span> &#123;&#125;</span><br></pre></td></tr></table></figure>

<p>然后根据模型类型去返回不同的cell高度</p>
<h3 id="实现判断逻辑，返回高度"><a href="#实现判断逻辑，返回高度" class="headerlink" title="实现判断逻辑，返回高度"></a>实现判断逻辑，返回高度</h3><p>在上面代码内部判断，此处模拟代码，如果我们需要在<code>indexPath.row == 3</code>的时候动态设置高度</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> (indexPath.row == <span class="number">0</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">10</span></span><br><span class="line">&#125; <span class="keyword">else</span> <span class="keyword">if</span> (indexPath.row == <span class="number">1</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">20</span></span><br><span class="line">&#125; <span class="keyword">else</span> <span class="keyword">if</span> (<span class="number">3</span>) &#123;</span><br><span class="line">    <span class="keyword">self</span>.tableView.rowHeight = <span class="type">UITableView</span>.automaticDimension</span><br><span class="line">    <span class="keyword">self</span>.tableView.estimatedRowHeight = <span class="number">100</span></span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">self</span>.tableView.rowHeight</span><br><span class="line">&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">50</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="在cell内部重写下面的方法"><a href="#在cell内部重写下面的方法" class="headerlink" title="在cell内部重写下面的方法"></a>在<code>cell</code>内部重写下面的方法</h3><p>我这里是<code>tableviewcell</code>嵌套了<code>collectionviewcell</code>，而<code>collectionviewcell</code>的内容是不固定的。需要根据内容决定<code>collectionview</code>的高度</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">override</span> <span class="function"><span class="keyword">func</span> <span class="title">systemLayoutSizeFitting</span><span class="params">(<span class="number">_</span> targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority)</span></span> -&gt; <span class="type">CGSize</span> &#123;</span><br><span class="line">    <span class="keyword">let</span> size = <span class="keyword">super</span>.systemLayoutSizeFitting(targetSize, withHorizontalFittingPriority: horizontalFittingPriority, verticalFittingPriority: verticalFittingPriority)</span><br><span class="line">    <span class="keyword">self</span>.tagV.setNeedsLayout()</span><br><span class="line">    <span class="keyword">self</span>.tagV.layoutIfNeeded()</span><br><span class="line">    <span class="keyword">let</span> height = <span class="keyword">self</span>.tagV.collectionViewLayout.collectionViewContentSize.height</span><br><span class="line">    <span class="keyword">return</span> <span class="type">CGSize</span>(width: size.width,height: size.height + height)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>




    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/iOS/" rel="tag"># iOS</a>
              <a href="/tags/UICollectionView/" rel="tag"># UICollectionView</a>
              <a href="/tags/UITableViewCell/" rel="tag"># UITableViewCell</a>
              <a href="/tags/UICollectionViewCell/" rel="tag"># UICollectionViewCell</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2020/08/06/Hexo%E6%90%AD%E5%BB%BA/" rel="prev" title="Hexo搭建">
      <i class="fa fa-chevron-left"></i> Hexo搭建
    </a></div>
      <div class="post-nav-item">
    <a href="/2020/08/08/Docker/" rel="next" title="Docker">
      Docker <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%AD%A3%E6%96%87"><span class="nav-text">正文</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%AE%BE%E7%BD%AE%E4%BB%A3%E7%90%86%E5%92%8C%E6%95%B0%E6%8D%AE%E6%BA%90%EF%BC%8C%E5%AE%9E%E7%8E%B0%E4%BB%A3%E7%90%86%E6%96%B9%E6%B3%95"><span class="nav-text">设置代理和数据源，实现代理方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%AE%9E%E7%8E%B0%E5%88%A4%E6%96%AD%E9%80%BB%E8%BE%91%EF%BC%8C%E8%BF%94%E5%9B%9E%E9%AB%98%E5%BA%A6"><span class="nav-text">实现判断逻辑，返回高度</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%9C%A8cell%E5%86%85%E9%83%A8%E9%87%8D%E5%86%99%E4%B8%8B%E9%9D%A2%E7%9A%84%E6%96%B9%E6%B3%95"><span class="nav-text">在cell内部重写下面的方法</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="favourite_s"
      src="/images/avatar.gif">
  <p class="site-author-name" itemprop="name">favourite_s</p>
  <div class="site-description" itemprop="description">只要胆子大，底牌全是炸</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">5</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">2</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">5</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">favourite_s</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-area"></i>
    </span>
    <span title="站点总字数">18k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">16 分钟</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>


  <script defer src="/lib/three/three.min.js"></script>


  




  
<script src="/js/local-search.js"></script>













  

  

</body>
</html>
